<?php
namespace app\admin\controller;

use app\common\model\user\Users;
use think\Db;
use app\common\model\user\UserActParam;
use think\Exception;
use app\common\model\user\UserActCash;
use app\common\model\coin\CoinList;
use app\common\controller\Log;
use app\common\model\user\UserActRecharge;
use app\common\controller\Finance;

class Act extends Base
{
	public function actList()
	{
		$data = $this->request->post('');
		$where = ['is_act' => 1];
		if(!empty($data['mobile']))$where['mobile'] = $data['mobile'];
		$list = Users::where($where)->order('id desc')->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['team_num'] = Users::where(['act_id' => $rows['id']])->count();
			$rows['finance'] = $this->getTradeList($rows['id']);
		}
		return jsonSuccess($list);
	}
	/**
	 * 历史汇总
	 * @param unknown $data
	 * @return number[][]
	 */
	private function getTradeList($user_id)
	{
		$start_time = strtotime(date('Y-m-d').'00:00:00');
		$end_time = strtotime(date('Y-m-d').'23:59:59');
		//初始化查询条件
		$where_buy = ['trade_style' => 1,'close' => ['exp',Db::raw('> buy_price')],'state' => ['neq',2]];
		$where_sale = ['trade_style' => 2,'close' => ['exp',Db::raw('< buy_price')],'state' => ['neq',2]];
		$where_buy_down = ['trade_style' => 1,'close' => ['exp',Db::raw('< buy_price')],'state' => ['neq',2]];
		$where_sale_down = ['trade_style' => 2,'close' => ['exp',Db::raw('> buy_price')],'state' => ['neq',2]];
		$where_day_buy = ['create_time' => ['between',[$start_time,$end_time]],'trade_style' => 1,'close' => ['exp',Db::raw('> buy_price')],'state' => ['neq',2]];
		$where_day_buy_down = ['create_time' => ['between',[$start_time,$end_time]],'trade_style' => 1,'close' => ['exp',Db::raw('< buy_price')],'state' => ['neq',2]];
		$where_day_sale = ['create_time' => ['between',[$start_time,$end_time]],'trade_style' => 2,'close' => ['exp',Db::raw('< buy_price')],'state' => ['neq',2]];
		$where_day_sale_down = ['create_time' => ['between',[$start_time,$end_time]],'trade_style' => 2,'close' => ['exp',Db::raw('> buy_price')],'state' => ['neq',2]];
		$where_fee = ['state' => ['neq',2]];
		$where_fee_day =['create_time' => ['between',[$start_time,$end_time]],'state' => ['neq',2]];
		
		
		//获取所有会员
		$user_ids = Users::where(['act_id' => $user_id])->column('id');
		$where_buy['user_id'] = ['in',$user_ids];;
		$where_sale['user_id'] = ['in',$user_ids];;
		$where_buy_down['user_id'] = ['in',$user_ids];;
		$where_sale_down['user_id'] = ['in',$user_ids];;
		$where_day_buy['user_id'] = ['in',$user_ids];;
		$where_day_buy_down['user_id'] = ['in',$user_ids];;
		$where_day_sale['user_id'] = ['in',$user_ids];;
		$where_day_sale_down['user_id'] = ['in',$user_ids];;
		$where_fee['user_id'] = ['in',$user_ids];;
		$where_fee_day['user_id'] = ['in',$user_ids];;
		
		/* if(!empty($data['times'])) {
			$times = $data['times'];
			$times[0] = strtotime($times[0]);
			$times[1] = strtotime($times[1]);
			$where_buy['create_time'] = ['between',$times];
			$where_sale['create_time'] = ['between',$times];
			$where_buy_down['create_time'] = ['between',$times];
			$where_sale_down['create_time'] = ['between',$times];
			$where_fee['create_time'] = ['between',$times];
		} */
		//总手续费
		$fee = Db::name('trade_leveraged')->where($where_fee)->sum('fee');
		//总盈利
		$loss_up_buy = Db::name('trade_leveraged')->where($where_buy)->sum('real_price');
		$loss_up_sale = Db::name('trade_leveraged')->where($where_sale)->sum('real_price');
		$loss_up = $loss_up_buy + $loss_up_sale;
		//总亏损
		$loss_down_buy = Db::name('trade_leveraged')->where($where_buy_down)->sum('real_price');
		$loss_down_sale = Db::name('trade_leveraged')->where($where_sale_down)->sum('real_price');
		$loss_down = $loss_down_buy + $loss_down_sale;
		//今日手续费
		$fee_day = Db::name('trade_leveraged')->where($where_fee_day)->sum('fee');
		//今日盈利
		$loss_up_buy = Db::name('trade_leveraged')->where($where_day_buy)->sum('real_price');
		$loss_up_sale = Db::name('trade_leveraged')->where($where_day_sale)->sum('real_price');
		$loss_up_day = $loss_up_buy + $loss_up_sale;
		//今日亏损
		$loss_down_buy = Db::name('trade_leveraged')->where($where_day_buy_down)->sum('real_price');
		$loss_down_sale = Db::name('trade_leveraged')->where($where_day_sale_down)->sum('real_price');
		$loss_down_day = $loss_down_buy + $loss_down_sale;
		$res = [
				'all' => [
						'fee' => $fee,
						'loss_up' => $loss_up,
						'loss_down' => $loss_down
				],
				'day' => [
						'fee' => $fee_day,
						'loss_up' => $loss_up_day,
						'loss_down' => $loss_down_day
				]
		];
		return $res;
	}
	
	/**
	 * 获取代理参数
	 * @return unknown
	 */
	public function getActParam()
	{
		$user_id = $this->request->post('user_id');
		$where = [];
		$where['user_id'] = $user_id ? $user_id : 0;
		$param = UserActParam::where($where)->find();
		return jsonSuccess($param);
	}
	
	/**
	 * 修改代理参数1
	 * @return unknown
	 */
	public function changeActParam()
	{
		$data = $this->request->post('');
		try {
			if(empty($data['id'])) {
				$data['create_time'] = time();
				$data['update_time'] = time();
				UserActParam::create($data);
			} else {
				unset($data['create_time']);
				$data['update_time'] = time();
				$act_param = UserActParam::get($data['id']);
				$act_param->save($data);
			}
		} catch (Exception $e) {
			return jsonError($e->getMessage());
		}
		return jsonSuccess('设置成功');
	}
	
	/**
	 * 获取提币、充币汇总
	 * @return unknown
	 */
	public function rechargeGather()
	{
		$data = $this->request->post(''); //获取客户端传递的数据
		$start_time = strtotime(date('Y-m-d').'00:00:00');
		$end_time = strtotime(date('Y-m-d').'23:59:59');
		$where = ['state' => 1]; //初始化查询条件
		$where_day = ['state' => 1,'create_time' => ['between',[$start_time,$end_time]]];
		//获取查询表1提币，0充币
		$style = $this->request->post('style');
		$cash = $style ? new UserActCash() : new UserActRecharge();
		//获取币种列表
		$coin_list = CoinList::where(['state' => 1])->select();
		$info = [];
		if(!empty($data['user_name'])){
			$user_id = Users::where(['user_name' => $data['user_name']])->value('id');
			$where['user_id'] = $user_id;
			$where_day['user_id'] = $user_id;
		}
		if(!empty($data['times'])) {
			$start_time = strtotime($data['times'][0]);
			$end_time = strtotime($data['times'][1]);
			$where['create_time'] = ['between',[$start_time,$end_time]];
		}
		foreach ($coin_list as $rows) {
			$all_num = $cash->where($where)->sum('price');
			$day_num = $cash->where($where_day)->sum('price');
			$temp = [
					'coin_name' => $rows['name'],
					'all_num' => $all_num,
					'day_num' => $day_num
			];
			$info[] = $temp;
		}
		return jsonSuccess($info);
	}
	
	/**
	 * 提币列表
	 * @return unknown
	 */
	public function cashList()
	{
		$data = $this->request->post(''); //获取客户端传递的数据
		$where = []; //初始化查询条件
		//重组查询数据
		if(!empty($data['user_name'])){
			$where['user_id'] = Users::where(['user_name' => $data['user_name']])->value('id');
		}
		if(!empty($data['times'])) {
			$start = strtotime($data['times'][0]);
			$end = strtotime($data['times'][1]);
			$where['create_time'] = ['between',[$start,$end]];
		}
		$list = UserActCash::where($where)->order('id desc')->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['user_info'] = Users::get($rows['user_id']);
		}
		return jsonSuccess($list);
	}
	
	/**
	 * 同意提币
	 * @throws Exception
	 * @return unknown
	 */
	public function agreeCash()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$cash = UserActCash::get($id);
			$user = Users::get($cash->user_id);
			if($cash->state)throw new Exception('状态错误');
			//更改状态
			$update = ['state' => 1 , 'update_time' => time()];
			$cash->save($update);
			//添加日志
			Log::addLog(2, "同意代理{$user->user_name}提币申请");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('同意成功');
	}
	
	/**
	 * 拒绝提币
	 * @throws Exception
	 * @return unknown
	 */
	public function refuseCash()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$cash = UserActCash::get($id);
			$user = Users::get($cash->user_id);
			if($cash->state)throw new Exception('状态错误');
			//更改状态
			$update = ['state' => 2 , 'update_time' => time()];
			$cash->save($update);
			//增加用户响应的可用金额
			Users::where(['id' => $cash->user_id])->setInc('bail',$cash->price);
			//添加财务
			$finance = new Finance();
			$finance->addActFinance($cash->user_id, $cash->user_id, $cash->price, "拒绝提币退回{$cash->price}", 2);
			//添加日志
			Log::addLog(2, "拒绝用户{$user->user_name}提币申请");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('拒绝成功');
	}
	
	/**
	 * 充币列表
	 * @return unknown
	 */
	public function rechargeList()
	{
		$data = $this->request->post(''); //获取客户端传递的数据
		$where = []; //初始化查询条件
		//重组查询数据
		if(!empty($data['user_name'])){
			$where['user_id'] = Users::where(['user_name' => $data['user_name']])->value('id');
		}
		if(!empty($data['times'])) {
			$start = strtotime($data['times'][0]);
			$end = strtotime($data['times'][1]);
			$where['create_time'] = ['between',[$start,$end]];
		}
		$list = UserActRecharge::where($where)->order('id desc')->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['user_info'] = Users::get($rows['user_id']);
		}
		return jsonSuccess($list);
	}
	
	/**
	 * 同意充币
	 * @throws Exception
	 * @return unknown
	 */
	public function agreeRecharge()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$recharge = UserActRecharge::get($id);
			if($recharge->state != 0)throw new Exception('状态错误');
			$recharge->save(['update_time' => time(),'state' => 1]);
			//添加财务
			Users::where(['id' => $recharge->user_id])->setInc('bail',$recharge->price);
			$finance = new Finance();
			$finance->addActFinance($recharge->user_id, $recharge->user_id, $recharge->price, "充值保证金成功", 1);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('同意成功');
	}
	
	/**
	 * 拒绝充币
	 * @throws Exception
	 * @return unknown
	 */
	public function refuseRecharge()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$recharge = UserActRecharge::get($id);
			if($recharge->state != 0)throw new Exception('状态错误');
			$recharge->save(['update_time' => time(),'state' => 2]);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('拒绝成功');
	}
	
	/**
	 * 修改保证金
	 * @return unknown
	 */
	public function updateBail()
	{
		$data = $this->request->post('');
		try {
			$user = Users::get($data['id']);
			$user->save($data);
		} catch (Exception $e) {
			return jsonError($e->getMessage());
		}
		return jsonSuccess('修改成功');
	}
}